<template>
  <div class="accessory">
    <!-- 表单搜索 -->
    <div class="form">
      <el-form label-position="right" :inline="true" :model="searchForm">
        <el-form-item label="分类" class="formItem">
          <el-select v-model="searchForm.assortId" clearable placeholder="分类">
            <el-option v-for="assort in assortList" :key="assort.id" :label="assort.name" :value="assort.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="配件名称" class="formItem">
          <el-input v-model="searchForm.name" placeholder="请输入配件名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="reset">重置</el-button>
          <el-button @click="addDialogVisible = true">新增配件</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-divider />
    <div v-if="tableList.length > 0" class="table">
      <!-- 表格展示 -->
      <el-table :data="tableList" stripe style="width: 100%" v-loading="tableLoading">
        <el-table-column prop="name" label="配件名称" width="150" />
        <el-table-column prop="assortName" label="分类" />
        <el-table-column prop="sellPrice" label="销售价格" />
        <el-table-column prop="inputPrice" label="进货价" />
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column prop="updateTime" label="修改时间"  />
        <el-table-column fixed="right" label="操作" >
          <template #default="scope">
            <el-button link type="primary" size="small" @click="showUpdate(scope.row.id)">修改</el-button>
            <el-button link type="danger" size="small" @click="deleteData(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-if="tableList.length > 0" style="float: right">

      <!-- 分页 -->
      <el-pagination v-model:current-page="pageInfo.pageNum" v-model:page-size="pageInfo.pageSize"
        :page-sizes="[10, 15, 20]" :total="pageInfo.total" :disabled="false" background
        layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
    <!-- 空状态 -->
    <div v-if="tableList.length <= 0">
      <el-empty description="暂无数据" />
    </div>
  </div>

  <!-- 新增弹出框 -->
  <el-dialog v-model="addDialogVisible" title="新增配件" width="40%">
    <div class="addForm">
      <el-form :label-position="'right'" :model="addform">
        <el-form-item label="配件分类" class="addFormItem">
          <el-select filterable allow-create default-first-option :reserve-keyword="false" v-model="addform.assortId"
                     clearable placeholder="分类" @change="selectAssort">
            <el-option v-for="assort in assortList" :key="assort.id" :label="assort.name" :value="assort.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="配件名称" class="addFormItem">
          <el-input v-model="addform.name" placeholder="请输入配件名称" clearable />
        </el-form-item>
        <el-form-item label="销售价格" class="addFormItem">
          <el-input v-model="addform.sellPrice" placeholder="请输入配件的销售价格" type="number" />
        </el-form-item>

        <el-form-item label="进货价格" class="addFormItem">
          <el-input v-model="addform.inputPrice" placeholder="进货价格" type="number" />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <el-button type="primary" @click="accessoryAdd">新增</el-button>
      <el-button type="info" @click="addDialogVisible = false">取消</el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="updateDialogVisible" title="修改配件" width="40%">
    <div class="addForm">
      <el-form :label-position="'right'" :model="updateForm">
        <el-form-item label="配件名称" class="addFormItem">
          <el-input v-model="updateForm.name" placeholder="请输入配件名称" clearable />
        </el-form-item>
        <el-form-item label="配件分类" class="addFormItem">
          <el-select filterable allow-create default-first-option :reserve-keyword="false" v-model="updateForm.assortId"
            clearable placeholder="分类" @change="selectAssort">
            <el-option v-for="assort in assortList" :key="assort.id" :label="assort.name" :value="assort.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="销售价格" class="addFormItem">
          <el-input v-model="updateForm.sellPrice" placeholder="请输入配件的销售价格" type="number" />
        </el-form-item>

        <el-form-item label="进货价格" class="addFormItem">
          <el-input v-model="updateForm.inputPrice" placeholder="进货价格" type="number" />
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <el-button type="primary" @click="updateData">修改</el-button>
      <el-button type="info" @click="updateDialogVisible = false">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { list, addAssort } from "@/api/assort.js"
import { addAccessory, pageList, deleteById, getById, updateById } from '@/api/accessory.js';
import { onMounted, reactive, ref } from "vue";
import { ElLoading, ElMessageBox } from 'element-plus'


const tableLoading = ref(false);
// 新增弹框是否显示
const addDialogVisible = ref(false);
// 修改弹框是否显示
const updateDialogVisible = ref(false);

// 表格展示数据
const tableList = ref([]);
// 分页数据
const pageInfo = reactive({
  total: 0,
  pageNum: 1,
  pageSize: 10,
});
// 分类列表
const assortList = ref([]);
// 查询表单
const searchForm = reactive({
  name: null,
  assortId: null,
});

// 新增配件表单
const addform = reactive({
  assortId: null,
  name: '',
  sellPrice: null,
  inputPrice: null
})

// 修改表单
let updateForm = reactive({
  id: null,
  assortId: null,
  name: '',
  sellPrice: null,
  inputPrice: null
});

onMounted(async () => {

  await listAssort()
  // 查询所有配件信息
  await search()

})

// 分页查询
const search = async () => {
  try {
    // 开启加载
    tableLoading.value = true;
    const response = await pageList(pageInfo, searchForm);
    tableList.value = response.data.data.list;
    pageInfo.total = response.data.data.total;
  } finally {
    tableLoading.value = false;
  }
};

// 重置
const reset = async () => {
  // 从新赋值
  searchForm.name = null;
  searchForm.assortId = null;
  // 重新查询
  await search()
}

// 展示修改配件信息
const showUpdate = async (id) => {
  const response = await getById(id);
  console.log(response)
  const data = response.data.data;
  updateForm.id = data.id;
  updateForm.name = data.name;
  updateForm.assortId = data.assortId;
  updateForm.sellPrice = data.sellPrice;
  updateForm.inputPrice = data.inputPrice;
  // 显示弹框
  updateDialogVisible.value = true
}

// 修改数据
const updateData = async () => {
  const loading = ElLoading.service({ fullscreen: true })
  try {
    await updateById(updateForm);
    // 重新查询
    await search();
  } finally {
    // 关闭弹框
    updateDialogVisible.value = false;
    // 清空表单数据
    claerUpdateForm();
    // 停止加载
    loading.close();
  }
}

// 清空修改表单的数据
const claerUpdateForm = async () => {
  updateForm.id = null;
  updateForm.assortId = null;
  updateForm.sellPrice = null;
  updateForm.inputPrice = null;
}
// 删除数据
const deleteData = async (id) => {

  try {
    await ElMessageBox.confirm(
      '确定要删除配件吗?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    await deleteById(id);
    // 删除后，重新刷新列表
    await search();
  } catch (e) {
  }
}

// 选中分类
const selectAssort = async () => {
  // 选中的值
  const selectValue = addform.assortId;
  if (!selectValue) {
    // 清空值，不做新增判断
    return;
  }
  // 判断选中的值在分类列表中是否存在
  const accessory = assortList.value.find((item) => item.id === selectValue)
  if (accessory == undefined) {
    // 新增分类
    await addAssort(selectValue)
    // 重新查询所有分类
    await listAssort()
    // 清空重新选择
    addform.assortId = null
  }
}

// 查询所有分类信息
const listAssort = async () => {
  // 查询所有分类信息
  const response = await list()
  assortList.value = response.data.data
}

/**
 * 新增配件
 */
const accessoryAdd = async () => {
  const loading = ElLoading.service({ fullscreen: true })
  try {
    await addAccessory(addform)
    await search()
  } finally {
    // 关闭弹框
    addDialogVisible.value = false;
    // 清空表单数据
    claerAddForm();
    // 停止加载
    loading.close()
  }
}

// 清空表单
const claerAddForm = () => {
  addform.assortId = null;
  addform.inputPrice = null;
  addform.name = null;
  addform.sellPrice = null;
}


// 处理页数发生改变的方法
const handleSizeChange = async (pageSize)=>{
  pageInfo.pageSize = pageSize;
  await search();
}

// 页码大小发生改变
const handleCurrentChange = async (pageNum)=>{
  pageInfo.pageNum = pageNum;
  await search();
}
</script>

<style scoped>
.form {
  width: 100%;
  height: 100px;
}

.formItem {
  width: 240px;
}

.addForm {
  width: 300px;
  margin: auto;
}

.addFormItem {
  width: 300px;
}
</style>